package com.xiaoq.matrix.weibo.endpoint;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import com.xiaoq.apis.user.MerchantMgrInfo4Vo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.matrix.entity.ContentMediaAccountEntity;
import com.xiaoq.matrix.entity.ContentMediaEntity;
import com.xiaoq.matrix.service.IContentMediaAccountService;
import com.xiaoq.matrix.service.IContentMediaService;
import com.xiaoq.matrix.service.IMerchantMgrService;
import com.xiaoq.matrix.weibo.util.ArticleStatus;
import com.xiaoq.matrix.weibo.util.WeiBoUtil;
import com.xiaoq.matrix.weibo.vo.WeiBoVo;
import weibo4j.Oauth;
import weibo4j.http.AccessToken;
import weibo4j.model.WeiboException;

@RestController
@RequestMapping("/api/v1/weibo")
public class WeiBoEndpoint {


	@Autowired
	private IContentMediaAccountService contentMediaAccountSrv;

	@Autowired
	private IContentMediaService contetnMediaSrv;
	
	@Autowired
	private IMerchantMgrService merMgerSrv;
	
	private static final Logger LOG = LoggerFactory.getLogger(WeiBoEndpoint.class);

	@ApiOperation(value = "点击认证微博", notes = "根据超链接认证微博")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "认证微博") })
	@GetMapping(value = "/{userId}/weiBo", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> weiboOauth(@PathVariable(value="userId",required=false)@ApiParam(value="userId",required=false)String userId) {
		String openUrl = null;
		try {
			Oauth oauth = new Oauth();
			openUrl = oauth.authorize("code",userId);

		} catch (WeiboException e) {
			String errorMsg = "返回code出错";
			LOG.error(errorMsg, e);
			return GenericResponse.ng("认证信息出错");
		}

		return GenericDataResponse.okWithData(openUrl);

	}

	@ApiOperation(value = "获取微博返回的code", notes = "获取微博返回的code")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "获取微博返回的code") })

	@GetMapping(value = "/code", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public void getCode(
			@RequestParam(value = "code", required = false) @ApiParam(value = "code", required = false) String code,
			@RequestParam(value = "state", required = true) @ApiParam(value = "state", required = true) String state,
			HttpServletRequest request,HttpServletResponse response) {
		// state返回的是userId
		String out = "http://p0sd9v5tn.bkt.clouddn.com/success.html";
		String fail = "http://p0sd9v5tn.bkt.clouddn.com/fail.html";
		Oauth oauth = new Oauth();
		ContentMediaAccountEntity contentMediaAccount = null;
		try {
			AccessToken accessToken = oauth.getAccessTokenByCode(code);
			if(accessToken!= null){
				contentMediaAccount = getMediaAccount(accessToken);
			}else{
				
			}
			MerchantMgrInfo4Vo merchantMgr = merMgerSrv.findMerMger(state);
			if(merchantMgr!=null){
				String merChantId = merchantMgr.getMerchantId();
				if(StringUtils.isNotEmpty(merChantId)){
					contentMediaAccount.setMerchantId(merChantId); 
				}else{
					LOG.error("没有认证的商铺不能发文！");
					try {
						response.sendRedirect(fail);
					} catch (IOException e) {
						LOG.error(e.getMessage(),e);
					}
					
				}
				
				contentMediaAccountSrv.saveContentMediaAccount(contentMediaAccount);
				try {
					response.sendRedirect(out);
				} catch (IOException e) {
					LOG.error(e.getMessage(),e);
				}
				
			}else{
				String errorMsg = "merchantMgr获取值为空！";
				LOG.error(errorMsg);
				try {
					response.sendRedirect(fail);
				} catch (IOException e) {
					LOG.error(e.getMessage(),e);
				}
			}
			

		} catch (WeiboException e) {
			String errorMsg = "从微薄获取access_token失败";
			LOG.error(errorMsg, e);
			try {
				response.sendRedirect(fail);
			} catch (IOException e1) {
				LOG.error(e.getMessage(),e1);
			}
		}
	}

	
	
	@ApiOperation(value = "发微博", notes = "发微博")
	@ApiResponses({ @ApiResponse(code = 200, response = GenericResponse.class, message = "发微博") })
	@PostMapping(value = "/weibocon", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
	public ResponseEntity<?> sendArticle(
			@RequestBody WeiBoVo weiBoVo) {

		String mediaId = contetnMediaSrv.findContentMedia("新浪微博").getId();
		MerchantMgrInfo4Vo merchantMgrInfo = merMgerSrv.findMerMger(weiBoVo.getUserId());
		String merchantId =null;
		if(merchantMgrInfo!=null){
			merchantId = merchantMgrInfo.getMerchantId();
		}else{
			return GenericResponse.ng("对应的商店还没有认证");
		}
		ContentMediaAccountEntity contentMediaAccount = contentMediaAccountSrv.findContentMediaAccount(merchantId,
				mediaId);
		String access_token = contentMediaAccount.getToken();
		ArticleStatus ars=null;
		try {
			Map<String, String> weiBoParameter = new HashMap<>();
			weiBoParameter.put("title", weiBoVo.getTitle());
//			weiBoParameter.put("content", URLEncoder.encode(weiBoVo.getContent(), "UTF-8"));
			weiBoParameter.put("content", weiBoVo.getContent());
			weiBoParameter.put("cover", weiBoVo.getCover());
			weiBoParameter.put("summary", weiBoVo.getSummary());
			weiBoParameter.put("text", weiBoVo.getText());
			weiBoParameter.put("access_token", access_token);
			ars = WeiBoUtil.updateStatus(weiBoParameter);
			long code = ars.getCode();
			if(code==100000L){
				return GenericResponse.ok();
			}else{
				return GenericResponse.ng("错误码："+code+"错误信息："+ars.getMsg());
			}
//		} catch (UnsupportedEncodingException e) {
		} catch (Exception e) {
			String errorMsg = "URLEnCoding 编码出错";
			LOG.error(errorMsg, e);
			return GenericResponse.ng(errorMsg);
		}

	}


	protected ContentMediaAccountEntity getMediaAccount(AccessToken accessToken) {
		ContentMediaAccountEntity contentMediaAccount = new ContentMediaAccountEntity();
		String accessTokens = accessToken.getAccessToken();
		String refreshToken = accessToken.getRefreshToken();
		if(StringUtils.isNotEmpty(accessTokens)){
			contentMediaAccount.setToken(accessTokens);
			contentMediaAccount.setRefreshToken(refreshToken);
		}else{
			LOG.debug("accessTokens:"+accessTokens+"refreshToken:"+refreshToken);
			throw new RuntimeException("认证失败！");
		}
		
		Long currentTime = System.currentTimeMillis();
		contentMediaAccount.setTokenTime(currentTime);
		contentMediaAccount.setAccount(accessToken.getUid());
		contentMediaAccount.setTokenDuratio(Long.parseLong(accessToken.getExpireIn()));
		ContentMediaEntity contentMedia = contetnMediaSrv.findContentMedia("新浪微博");
		if(contentMedia!=null){
			String contentMediaId = contentMedia.getId();
			contentMediaAccount.setMediaId(contentMediaId);
			return contentMediaAccount;
		}else{
			LOG.error("查询不到对应的媒体！");
			return contentMediaAccount;
		}
		
		
		

	}

}
